package topofstack.networkserverutils;

import topofstack.networkserverutils.mail.SendMailSSL;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SmtpTest extends Activity {

	private EditText hostField;
	private EditText portField;
	private EditText emailField;
	private EditText passwordField;

	private Button submit;
	private ProgressDialog dialog;
	
	public static final String HOST_NAME = "host";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.send_mail);

		hostField = (EditText) findViewById(R.id.send_mail_server);
		portField = (EditText) findViewById(R.id.send_mail_port);
		emailField = (EditText) findViewById(R.id.send_mail_username);
		passwordField = (EditText) findViewById(R.id.send_mail_password);

		submit = (Button) findViewById(R.id.send_mail_submit);

		submit.setOnClickListener(new View.OnClickListener() {

			public void onClick(View arg0) {
				new RetriveData().execute(new Void[0]);
				showProgressDialog();
			}
		});
		
		String host = getIntent().getExtras().getString(HOST_NAME);
		hostField.setText("smtp." + host);
	}
	
	private void showProgressDialog() {
		dialog = new ProgressDialog(this);
		dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		dialog.setMessage("Sending Test Email...");
		dialog.setIndeterminate(true);
		dialog.show();
	}

	private class RetriveData extends AsyncTask<Void, Void, Boolean> {

		@Override
		protected Boolean doInBackground(Void... params) {
			String host = hostField.getText().toString();
			String port = portField.getText().toString();
			String email = emailField.getText().toString();
			String password = passwordField.getText().toString();
			
			SendMailSSL sendMailSSL = new SendMailSSL();
			return sendMailSSL.send(host, port, email, password);
		}
		
		@Override
		protected void onPostExecute(Boolean result) {
			if(result) {
				Toast.makeText(getBaseContext(), "SMTP Ok", 
						Toast.LENGTH_SHORT).show();
			}
			else {
				Toast.makeText(getBaseContext(), "SMTP Failed", 
						Toast.LENGTH_SHORT).show();
			}
			dialog.cancel();
			finish();
		}
	}
}
